﻿using System;
using System.Windows.Forms;
using FBroSharp;             // ⚠️ #1 MOST CRITICAL! FBroSharpControl, FBroSharpBrowserListControl - ALWAYS FIRST!
using FBroSharp.Lib;         // ⚠️ CRITICAL! IFBroSharpBrowser, IFBroSharpFrame
using FBroSharp.Value;       // ⚠️ CRITICAL! FBroSharpWindowsInfo, FBroSharpBrowserSetting
using FBroSharp.Event;       // FBroSharpBrowserEvent
using FBroSharp.DataType;    // ⚠️ REQUIRED! FBroSharpEventDisableControl (struct!)
using FBroSharp.Const;       // FBroSharpTransitionType
using FBroSharp.Callback;    // Callback types

namespace FBroBrowserAutomation
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "main_browser";

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 创建嵌入式浏览器
            CreateEmbeddedBrowser();
        }

        /// <summary>
        /// 创建嵌入式浏览器
        /// </summary>
        private void CreateEmbeddedBrowser()
        {
            try
            {
                // 创建窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // ⚠️ CRITICAL for embedded browser!
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "FBro浏览器"
                };

                // 创建浏览器设置
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // ⚠️ CRITICAL: event_control 参数使用 default，不能用 null（struct value type）
                bool success = FBroSharpControl.CreatBrowser(
                    "https://www.baidu.com",
                    windowInfo,
                    settings,
                    null,  // request_context - OK (reference type)
                    null,  // extra_info - OK (reference type)
                    browserEvent,
                    default,  // ✅ Use default for struct value types!
                    BROWSER_USER_FLAG
                );

                if (success)
                {
                    UpdateStatus("浏览器创建中...");
                }
                else
                {
                    MessageBox.Show("浏览器创建失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建浏览器时出错: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 获取浏览器实例
        /// </summary>
        private IFBroSharpBrowser GetBrowser()
        {
            var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
            if (browser == null || !browser.IsValid)  // ⚠️ IsValid is PROPERTY, not method!
            {
                return null;
            }
            return browser;
        }

        /// <summary>
        /// 导航到指定URL
        /// </summary>
        private void btnGo_Click(object sender, EventArgs e)
        {
            try
            {
                string url = txtUrl.Text.Trim();
                if (string.IsNullOrEmpty(url))
                {
                    MessageBox.Show("请输入URL地址", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确保URL有协议前缀
                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    url = "https://" + url;
                }

                var browser = GetBrowser();
                if (browser != null)
                {
                    var mainFrame = browser.GetMainFrame();
                    if (mainFrame != null)
                    {
                        mainFrame.LoadURL(url);
                        UpdateStatus($"正在导航到: {url}");
                    }
                }
                else
                {
                    MessageBox.Show("浏览器未就绪", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新页面
        /// </summary>
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = GetBrowser();
                if (browser != null)
                {
                    browser.Reload();
                    UpdateStatus("正在刷新页面...");
                }
                else
                {
                    MessageBox.Show("浏览器未就绪", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 后退
        /// </summary>
        private void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = GetBrowser();
                if (browser != null)
                {
                    if (browser.CanGoBack())
                    {
                        browser.GoBack();
                        UpdateStatus("后退");
                    }
                }
                else
                {
                    MessageBox.Show("浏览器未就绪", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"后退失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 前进
        /// </summary>
        private void btnForward_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = GetBrowser();
                if (browser != null)
                {
                    if (browser.CanGoForward())
                    {
                        browser.GoForward();
                        UpdateStatus("前进");
                    }
                }
                else
                {
                    MessageBox.Show("浏览器未就绪", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"前进失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// ⚠️ MANDATORY: 窗体大小改变时调整浏览器大小
        /// 这是嵌入式浏览器的必需实现！
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// ⚠️ MANDATORY: Panel大小改变时调整浏览器大小
        /// </summary>
        private void panelBrowser_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = GetBrowser();
                if (browser != null)
                {
                    // 调整浏览器大小以匹配容器
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 窗体关闭时清理资源
        /// </summary>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                var browser = GetBrowser();
                if (browser != null)
                {
                    // 关闭浏览器
                    browser.CloseBrowser(false, false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭浏览器失败: {ex.Message}");
            }
        }

        #region 从BrowserEvent调用的公共方法（必须是public或internal）

        /// <summary>
        /// 更新状态栏（线程安全）
        /// </summary>
        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(message)));
                return;
            }
            lblStatus.Text = message;
        }

        /// <summary>
        /// 更新URL文本框（线程安全）
        /// </summary>
        public void UpdateUrlTextBox(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateUrlTextBox(url)));
                return;
            }
            txtUrl.Text = url;
        }

        /// <summary>
        /// 更新窗体标题（线程安全）
        /// </summary>
        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }
            this.Text = $"{title} - FBro浏览器";
        }

        /// <summary>
        /// 更新导航按钮状态（线程安全）
        /// </summary>
        public void UpdateNavigationButtons(bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateNavigationButtons(canGoBack, canGoForward)));
                return;
            }
            btnBack.Enabled = canGoBack;
            btnForward.Enabled = canGoForward;
        }

        #endregion
    }
}
